package com.melody.common.interceptors;

import com.melody.utils.JwtUtil;
import com.melody.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author:
 * @Description: 将获得的token解析出来，保存到ThreadLocal中
 * @DateTime: 2024/10/9 15:47
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的token
        String jwt = request.getHeader("Authorization");
        //3.判断用户是否存在
        if (jwt == null || jwt.equals("") ){
            //4.不存在拦截
            System.out.println("不存在token就 -----------拦截了  返回401 ------------");
            response.setStatus(401);
            return false;
        }else {
            //5.存在 保存用户信息（先解析token）到ThreadLocal
            try{
                jwt = jwt.substring(7); // 去掉前面7个字符   "Bearer " 部分
                Map<String, Object> tokenMap = JwtUtil.parseToken(jwt);
                ThreadLocalUtil.set(tokenMap);

                // 在后续代码中获取ThreadLocal中的信息
                Map<String, Object> userInfo = ThreadLocalUtil.get();
//                System.out.println("---------User Info from ThreadLocal: " + userInfo);
            }catch (Exception e){
//                System.out.println("解析token失败 -----------拦截了  返回401 ------------");
                response.setStatus(401);
                return false;
            }
            //6.放行
            return true;
        }
    }
}
